<?php
namespace App\Models\System;

use App\Exceptions\ApiException;
use App\Providers\LengthAwarePaginatorProvider;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Enums\System\SysConfig\{ConfigType};

/**
* 参数配置表 模型
* @create 2023-08-21 17:07:51
*/
class SysConfigModel extends \App\Models\BaseModel {
    use HasFactory;

    const Table			= "sys_config";
    const PrimaryKey	= "config_id";
    public $timestamps	= true;

    static $Wheres = [ // 直接定义column, 默认where(column, '=', value)
        'config_id', 'config_key', 'config_name', 'config_type'
    ];
    public function __construct($attributes = []) {
        parent::__construct($attributes);

        static::$Wheres['begin_time']   = fn($q, $v) => $q->whereDate(atn('create_time'), '>=', $v);    // ymd
        static::$Wheres['end_time']     = fn($q, $v) => $q->whereDate(atn('create_time'), '<=', $v);    // ymd
    }

    /** 是否为系统内置 */
    public function scopeConfigType($query, $type='Y') { return $query->where('config_type', '=', $type); }

    /** ========== 常用查询 ========== */
    static $Vo  = ['config_id','config_name','config_key','config_value','config_type','create_by','create_time','update_by','update_time','remark'];
    static $Voi = ['*', ];

    
    /**
     * 查询参数配置信息
     * 
     * @param array|SysConfigModel $config 参数配置信息
     * @return SysConfigModel 参数配置信息
     */
    public function selectConfig(array $config): SysConfigModel {
        return throw_str(
            $this->selectVo()
                ->wheres($config, 'config_id', 'config_key')
                ->first()
            ?? "配置(". $config['configId'] ?? $config['configKey'] .")查找失败");
    }

    /**
     * 通过ID查询配置
     * 
     * @param $configId 参数ID
     * @return SysConfigModel 参数配置信息
     */
    public function selectConfigById(int $configId): SysConfigModel {
        return throw_str(
            $this->selectVo()
                ->where(atn('config_id'), '=', $configId)
                ->first() 
            ?? "配置({$configId})查找失败");
    }

    /**
     * 查询参数配置列表
     * 
     * @param $config 参数配置信息
     * @return SysConfigModel[]|Collection 参数配置集合
     */
    public function selectConfigList(array $config): Collection {
        return $this->selectVo()
            ->wheres($config, 'config_name', 'config_type', 'config_key', 'begin_time', 'end_time')
            ->get()
            ;
    }

    /**
     * 根据键名查询参数配置信息
     * 
     * @param $configKey 参数键名
     * @return null|SysConfigModel 参数配置信息
     */
    public function checkConfigKeyUnique($configKey): ?SysConfigModel {
        return $this->selectVo()
                ->where(atn('config_key'), '=', $configKey)
                ->first()
                ;
        // return throw_str(
        //     ?? "配置({$configKey})查找失败");
    }

    /**
     * 新增参数配置
     * 
     * @param $config 参数配置信息
     * @return int 结果
     */
    public function insertConfig(array $config): SysConfigModel {
        $values = static::when($config, 'config_name', 'config_key', 'config_value', 'config_type', 'create_by', 'remark',);
        return throw_str(
            static::row_add($values)
        );
    }

    /**
     * 修改参数配置
     * 
     * @param $config 参数配置信息
     * @return int 结果
     */
    public function updateConfig(array $config): int {
        $values = static::when($config, 'config_name', 'config_key', 'config_value', 'config_type', 'create_by', 'remark',);
        return $this
                ->where('config_id', '=', get_value($config, static::PrimaryKey))
                ->update($values);
    }

    /**
     * 删除参数配置
     * 
     * @param int configId 参数ID
     * @return 结果
     */
    public function deleteConfigById($configId): int{
        return $this->deleteConfigByIds([$configId]);
    }

    /**
     * 批量删除参数信息
     * 
     * @param int[]|array $configIds 需要删除的参数ID
     * @return int 结果
     */
    public function deleteConfigByIds(array $configIds): int {
        return $this
                ->whereIn('config_id', $configIds)
                ->delete()
                ;
    }


    /** 根据ConfigId获取 */
    public function selectByConfigId($config_id): SysConfigModel {
        $where = [['config_id', '=', "{$config_id}"]];
        return throw_str(
            static::row($where) ?? "数据($config_id)为空~"
        );
    }


    /** 获取列表 @return SysConfig[]+paginator() */
    public function selectList(int|array $pag=1, array $param=[]): LengthAwarePaginatorProvider {
        return static::rows_pag($pag, [], fn($q)=>$q
                    // ->when(isset($param['config_id']), fn($q)=>$q->where('config_id', '=', $param['config_id']))
                    ->wheres($param, 'config_id','config_type')
                    ->orderByDesc("config_id")
        );
    }


    /** 插入数据 */
    public function insertData(array $data): SysConfigModel {
        return throw_str(
            static::row_add([
                // 'config_id' => $data['config_id'],
                'config_name' => $data['config_name'] ?? '',
                'config_key' => $data['config_key'] ?? '',
                'config_value' => $data['config_value'] ?? '',
                'config_type' => $data['config_type'] ?? 'N',
                'create_by' => $data['create_by'] ?? '',
                // 'create_time' => $data['create_time'] ?? '',
                'update_by' => $data['update_by'] ?? '',
                // 'update_time' => $data['update_time'] ?? '',
                'remark' => $data['remark'] ?? '',
            ])
        );
    }


    /** 更新数据 */
    public function updateData(int|array $idOrWhere, array $data): SysConfigModel {
        $values = static::when(
                    $data, 
                    // 'config_id',
                    'config_name',
                    'config_key',
                    'config_value',
                    'config_type',
                    'create_by',
                    // 'create_time',
                    'update_by',
                    // 'update_time',
                    'remark',
                );
        return throw_str(
            static::row_update($idOrWhere, $values)
        );
    }


    /** 删除数据 */
    public function deleteData(int|array $idOrWhere): SysConfigModel {
        return throw_str(
            static::row_delete($idOrWhere)
        );
    }




}